<template>
  <div class="home-form">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="180">
      <FormItem label="头像：">
        <!--<img class="home-photo" :src="upload">-->
        <img  v-show="editShow" class="home-photo"  :src="this.result.avatar?('http://192.168.1.249'+this.result.avatar):'/static/image/default_icon.jpg'">
        <img  v-show="!editShow" class="home-photo" style="cursor:pointer"   @click="selImg" id="upload" :src="this.result.avatar?('http://192.168.1.249'+this.result.avatar):'/static/image/default_icon.jpg'">
        <template>
          <div v-show="!editShow" style="width:300px;" >
            <!--<div class="demo-upload-list" v-for="item in uploadList">
              ![](item.url)
              <div class="demo-upload-list-cover">
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </div>-->
            <!--<Upload ref="upload" action="/usermgt/employee/1" v-model="formValidate.avatar" :show-upload-list="false" :format="['jpg','jpeg','png']" :max-size="2048" :before-upload="handleBeforeUpload" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" type="drag"  style="display: inline-block;width:58px;">
              <Button type="ghost" icon="ios-cloud-upload-outline">修改图片</Button>
            </Upload>-->
              <div style="position:absolute;top:0;left:0;visibility:hidden;cursor:pointer">
                <input type="file" ref="file" @change="getImg"  id="file" accept="image/jpg,image/jpeg,image/png" style="width:80px;height:80px;">
              </div>
          </div>
        </template>
      </FormItem>
      <FormItem label="用户名：" v-model="formValidate.userName">
        <span>{{this.result.userName}}</span>
        <Button s-show="hasButtonPermission('101020101')" v-show="editShow" @click="showEdits" class="margin-left-400">编辑个人资料</Button>
      </FormItem>
      <FormItem label="密码：" style="display:none;">
        <span v-model="formValidate.employeeName">*******</span>
        <!--<Button @click="showEditPassword" class="margin-left-400">修改密码</Button>-->
        <Modal v-model="editPasswordModal" title="修改密码" :closable='false' :mask-closable='false' class="home-pass" :width="700">
          <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right" :rules="passwordValidate">
            <FormItem label="当前密码：" prop="oldPass" :error="oldPassError">
              <div style="display:inline-block;width:300px;">
                <Input v-model="editPasswordForm.oldPass" placeholder="请输入当前密码" :value="radioed"/>
              </div>
              <input type="radio" v-model="radioed" value="111111" class="home-radio"/><span>初始化密码为<span>111111</span></span>
            </FormItem>
            <FormItem label="新密码：" prop="newPass">
              <div style="display:inline-block;width:300px;">
                <Input v-model="editPasswordForm.newPass" placeholder="请输入新密码，至少6位字符"/>
              </div>
            </FormItem>
            <FormItem label="确认新密码：" prop="rePass">
              <div style="display:inline-block;width:300px;">
                <Input v-model="editPasswordForm.rePass" placeholder="请输入确认新密码"/>
              </div>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="text" @click="cancelEditPass">取消</Button>
            <Button type="primary" :loading="savePassLoading" @click="saveEditPass">确认修改密码</Button>
          </div>
        </Modal>
      </FormItem>
      <FormItem label="员工姓名：" v-model="formValidate.employeeName">
        <span>{{this.result.employeeName}}</span>
      </FormItem>
      <FormItem label="昵称：" prop="nickName">
        <div v-show="!editShow" style="display:inline-block;width:300px;">
          <Input type="text" v-model="formValidate.nickName" :maxlength="255"/>
        </div>
        <span v-show="editShow">{{this.result.nickName}}</span>
      </FormItem>
      <FormItem label="性别：" prop="gender">
         <RadioGroup v-show="!editShow" @on-change="radioChange" v-model="formValidate.gender">
          <div v-if="this.result.gender === true || this.result.gender === false ">
           <Radio label="true" :checked="this.result.gender?true:false">男</Radio>
           <Radio label="false" :checked="this.result.gender?false:true">女</Radio>
          </div>
          <div v-else>
            <Radio label="true">男</Radio>
            <Radio label="false">女</Radio>
          </div>
        </RadioGroup>
       <!-- <div v-show="!editShow" v-model="formValidate.gender">
          <input type="radio" name="genders" :checked="this.result.gender?true:false">男
          <input type="radio" name="genders" :checked="this.result.gender?false:true">女
        </div>-->
        <span v-show="editShow">
          <span v-if="this.result.gender === true">男</span>
          <span v-else-if="this.result.gender === false">女</span>
          <span v-else></span>
        </span>
      </FormItem>

      <FormItem label="职能：" v-model="formValidate.orgFuncs">
        <span v-for="(arr) in this.funcNames">{{arr+"，"}}</span>
      </FormItem>
      <FormItem label="部门：" v-model="formValidate.orgStruct">
       <span>{{this.result.orgStruct?(this.result.orgStruct.dept):''}}</span>
      </FormItem>
      <FormItem label="联系方式：" class="home-phone" prop="contact">
        <div v-show="!editShow" style="display:inline-block;width:300px;">
          <Input v-model="formValidate.contact"/>
        </div>
        <span v-show="editShow">{{this.result.contact}}</span>
      </FormItem>
      <FormItem label="腾讯通：" v-model="formValidate.rtx">
        <span>{{this.result.rtx}}</span>
      </FormItem>
      <FormItem label="邮箱：" prop="email">
        <div v-show="!editShow" style="display:inline-block;width:300px;">
          <Input v-model="formValidate.email"/>
        </div>
        <span v-show="editShow">{{this.result.email}}</span>
      </FormItem>
      <FormItem label="入职时间：" v-model="formValidate.entryTime">
        <span> {{this.result.entryTime?(this.$moment(this.result.entryTime).format('YYYY-MM-DD')):''}}</span>
      </FormItem>
      <FormItem label="出生日期：" >
        <Row v-show="!editShow">
          <Col span="11">
          <FormItem prop="birthdate">
            <DatePicker type="date" v-model="formValidate.birthdate"></DatePicker>
          </FormItem>
          </Col>
        </Row>
        <span v-show="editShow">{{this.result.birthdate?(this.$moment(this.result.birthdate).format('YYYY-MM-DD')):''}}</span>
      </FormItem>
      <FormItem v-show="!editShow" style="margin-top: 30px;">
        <Button type="primary" @click="handleSubmit('formValidate')">保存</Button>
        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">取消</Button>
      </FormItem>
      <Spin size="large" fix v-if="spinShow">加载中...</Spin>
    </Form>
  </div>
</template>

<script>
    import { getUserApi ,putUserApi,getUpLoadApi ,getUserPersonalData } from '../../http/user.api'
    export default {
        name: 'User',
        data () {
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPass) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            }
            const valideTel = (rule, value, callback) => {
                let tel = /^0?(13[0-9]|15[012356789]|17[0135678]|18[0-9]|14[579])[0-9]{8}$/
                if(value && !tel.test(value)) {
                    callback(new Error('联系方式格式不正确'))
                } else {
                    callback()
                }
            }
            return {
                id:'',
                params:{
                    userId:''
                },
                avatar:{},
                addImg: {},
                spinShow: false,
                uploadList: [],
                editShow: true,
                modal1: false,
                radioed: '',
                result:{},
                funcNames:[],
                editPasswordModal: false, // 修改密码模态框显示
                oldPassError: '',
                savePassLoading: false,
                formValidate: {
                    avatar: '',
                    nickName: '',
                    gender: '',
                    email: '',
                    contact: '',
                    birthdate: ''
                },
                editPasswordForm: {
                    oldPass: '',
                    newPass: '',
                    rePass: ''
                },
                ruleValidate: {
                    nickName: [
                        // { required: true, message: '昵称不能为空', trigger: 'blur' }
                    ],
                    email: [
                        // { required: true, message: '邮箱不能为空', trigger: 'blur' },
                        { type: 'email', message: '电子邮件格式不正确', trigger: 'change' }
                    ],
                    contact: [
                        // { required: true, message: '联系方式不能为空', trigger: 'blur' },
                        { validator: valideTel, trigger: 'change' }
                    ],
                    gender: [
                        // { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    birthdate: [
                        // { required: true, type: 'date', message: '请选择日期', trigger: 'change' }
                    ]
                },
                passwordValidate: {
                    oldPass: [
                        { required: true, message: '请输入原密码', trigger: 'blur' }
                    ],
                    newPass: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                        { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                    ],
                    rePass: [
                        { required: true, message: '请再次输入新密码', trigger: 'blur' },
                        { validator: valideRePassword, trigger: 'blur' }
                    ]
                }
            }
        },
        created () {
           /*this.getUser()*/
            this.getUserData()
        },
        methods: {
            selImg: function () {
                const _this = this;
                _this.$refs.file.click() // 触发图片上传
            },
            getImg() {
                const _this = this;
                var imgs = _this.$refs['file'].files[0]
                var reader = new window.FileReader()
                reader.onload = (e) => {
                    _this.avatarFile = e.target.result
                    // console.log(_this.avatarFile)
                }
                // reader.readAsArrayBuffer(imgs) // 将file读取为ArrayBuffer
                reader.readAsDataURL(imgs) // 将file读取为Url
            },
            radioChange(){
                let ivu = document.getElementsByClassName("ivu-radio-wrapper")
                for(var i = 0; i<ivu.length ;i++){
                    ivu[i].parentNode.checked = false;
                }
            },
            hasButtonPermission(permission) {
                return this.$store.getters['login/hasButtonPermission'](permission);
            },
            showEdits (){
                this.getUserData()
                this.editShow = !this.editShow
                console.log("this.editShow===="+this.editShow)
            },
            showEditPassword () {
                this.editPasswordModal = true
            },
            cancelEditPass () {
                this.editPasswordModal = false
            },
            saveEditPass () {
                this.$refs['editPasswordForm'].validate((valid) => {
                    if (valid) {
                        this.savePassLoading = true
                        // you can write ajax request here
                    }
                })
            },
            getUserData(){
                getUserPersonalData().then(suc => {
                    const _this = this
                    _this.spinShow = true
                    localStorage.setItem('avatar',suc.data.result.avatar);
                    _this.result = suc.data.result
                    _this.userId = suc.data.result.id

                    /*_this.formValidate.avatar = suc.data.result.avatar*/
                    _this.formValidate.nickName = suc.data.result.nickName
                    _this.formValidate.email = suc.data.result.email
                    _this.formValidate.contact = suc.data.result.contact
                    /*_this.formValidate.gender = suc.data.result.gender*/
                   _this.formValidate.birthdate = _this.result.birthdate?(this.$moment(_this.result.birthdate).format('YYYY-MM-DD')):''
                    if(_this.result.orgFuncs){
                        _this.funcNames = _this.result.orgFuncs.map(item => item.funcName)
                    }
                    _this.spinShow = false
                })
            },
            getUser() {
                getUserApi(this.$route.params.id).then(suc => {
                    console.log("this.params.userId===" + this.params.userId)
                    this.result = suc.data.result
                    console.log("suc.data.result.employeeName======" + this.result.employeeName)
                    console.log('suc====' + suc)
                })
            },
            handleSubmit (name) {
                const _this = this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        _this.spinShow = true
                        var fd = new FormData()
                        console.log("this.userId666===="+_this.userId)
                        fd.append('avatarFile',document.getElementById('file').files[0])
                        putUserApi(fd,_this.formValidate,_this.userId).then(suc => {
                            console.log(suc)
                            _this.getUserData()
                            _this.spinShow = false
                            _this.editShow = true
                            _this.$Message.success('保存成功!')
                            location.reload()
                        }).catch(err => {
                            _this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                            _this.spinShow = false
                        })
//                    } else {
//                        this.$Message.error('保存失败!')
//                    }
                }
            })
            },
            // 上传头像
            getImg() {
                var imgs = document.getElementById('file').files[0]
                var reader = new window.FileReader()
                var addfm = new window.FormData()
                addfm.append('file', imgs)
                reader.onload = (e) => {
                    this.addImg = "files="+addfm
                    var img = document.getElementById('upload')
                    img.src = e.target.result
                }
                reader.readAsDataURL(imgs) // 将file读取为Url
            },
            handleReset (name) {
                this.$refs[name].resetFields()
                this.editShow = !this.editShow
            }
        }
    }
</script>

<style scoped>
.user{
  width: 100%;
  height: 100%;
}
</style>
